package com.gesonet.wechat.api;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import com.gesonet.common.utils.HttpsUtils;
import com.gesonet.common.utils.json.JsonUtils;
import com.gesonet.wechat.constants.MenuConstants;
import com.gesonet.wechat.model.common.Response;
import com.gesonet.wechat.model.common.WxToken;
import com.gesonet.wechat.model.menu.Button;

public class MenuApi {

	/**
	 * @Title: create 
	 * @Description: 创建自定义菜单
	 * @param token
	 * @param mainButtonList 主菜单列表:自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单
	 * 二级菜单请逻辑处理，一级菜单会mainButtonList.subList(0, 2) 获取前三
	 * @return Response
	 * @throws
	 */
	public static Response create(String token,List<Button> mainButtonList){
		String url = MessageFormat.format(MenuConstants.URL_CREATE, token);
		Map<String,List<Button>> paramMap = new HashMap<>(1);
		//自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。
		if(CollectionUtils.isNotEmpty(mainButtonList) && mainButtonList.size() > 3){
			mainButtonList = mainButtonList.subList(0, 2);
		}
		paramMap.put("button", mainButtonList);
		String json = HttpsUtils.httpsRequest(url, HttpsUtils.METHOD_GET, JsonUtils.toJSONString(paramMap));
		return (Response) JsonUtils.TO_OBJ(json, Response.class);
	}
	
	public static List<Button> get(String token){
		String url = MessageFormat.format(MenuConstants.URL_GET, token);
		String json = HttpsUtils.httpsRequest(url, HttpsUtils.METHOD_GET, null);
		if(StringUtils.isNotBlank(json)){
			return JsonUtils.json2List(json, Button.class);
		}else{
			return null;
		}
	}
	
	
	public static void main(String[] args) throws Exception {
		Button main = new Button();
		main.setName("一级主菜单");
		
		Button subButton1 = new Button();
		subButton1.setName("二级菜单1");
		subButton1.setType("view");
		subButton1.setUrl("http://www.baidu.com/");
		
		Button subButton2 = new Button();
		subButton2.setName("二级菜单2");
		subButton2.setType("view");
		subButton2.setUrl("http://www.sina.com/");
		
		List<Button> sub = new ArrayList<>();
		sub.add(subButton1);
		sub.add(subButton2);
		
		main.setSub_button(sub);

		List<Button> mainButtonList = new ArrayList<>(3);
		mainButtonList.add(main);
		
		Map<String,List<Button>> paramMap = new HashMap<>(1);
		paramMap.put("button", mainButtonList);
		
		System.out.println(JsonUtils.toJSONString(paramMap));
		
		String token = ((WxToken) CommonApi.getToken()).getAccess_token();
		
		System.out.println(create(token, mainButtonList).getErrcode());
		
		get(token);
	}
}
